<template>
  <div class="order-management">
    <h2>平台自营订单管理</h2>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单ID">
          <el-input
              v-model.number="searchForm.orderId"
              placeholder="请输入订单ID"
              clearable
              @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待处理" value="pending" />
            <el-option label="洗涤中" value="washing" />
            <el-option label="准备取件" value="ready_for_pickup" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单类型">
          <el-select v-model="searchForm.orderType" placeholder="请选择订单类型" clearable>
            <el-option label="洗衣套餐" value="package" />
            <el-option label="自定义选项" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单列表 -->
    <el-table
        :data="filteredOrders"
        style="width: 100%"
        border
        v-loading="loading"
        :default-sort="{ prop: 'orderId', order: 'descending' }"
        empty-text="暂无订单数据"
    >
      <el-table-column prop="orderId" label="订单ID" width="100" sortable />
      <el-table-column prop="userId" label="用户ID" width="100" />
      <el-table-column prop="deviceId" label="设备ID" width="100" />
      <el-table-column prop="orderAmount" label="订单金额" width="120" />
      <el-table-column prop="status" label="订单状态" width="150">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ statusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="paymentStatus" label="支付状态" width="120">
        <template #default="scope">
          <el-tag :type="getPaymentStatusTagType(scope.row.paymentStatus)">
            {{ paymentStatusText(scope.row.paymentStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180" sortable>
        <template #default="scope">
          {{ formatDateTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button type="primary" size="small" @click="viewOrderDetails(scope.row)">查看</el-button>
          <el-button type="danger" size="small" @click="deleteOrder(scope.row.orderId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        background
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="totalOrders"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
    />

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="订单详情" width="30%">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单ID">{{ selectedOrder.orderId }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ selectedOrder.userId }}</el-descriptions-item>
        <el-descriptions-item label="设备ID">{{ selectedOrder.deviceId }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">{{ selectedOrder.orderAmount }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">{{ statusText(selectedOrder.status) }}</el-descriptions-item>
        <el-descriptions-item label="支付状态">{{ paymentStatusText(selectedOrder.paymentStatus) }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(selectedOrder.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDateTime(selectedOrder.updatedAt) }}</el-descriptions-item>
        <el-descriptions-item label="套餐ID">{{ selectedOrder.packageId || 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="水量选项ID">{{ selectedOrder.waterOptionId || 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="程序选项ID">{{ selectedOrder.programId || 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="香味选项ID">{{ selectedOrder.scentId || 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="烘干选项ID">{{ selectedOrder.dryingId || 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="时长">{{ selectedOrder.duration || 0 }} 分钟</el-descriptions-item>
        <el-descriptions-item label="自助洗衣点ID">{{ selectedOrder.pointId || 'N/A' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import _ from 'lodash';

export default {
  name: 'SelfServiceOrderManagement',
  data() {
    return {
      selfServiceOrders: [],
      totalOrders: 0,
      pageSize: 10,
      currentPage: 1,
      dialogVisible: false,
      selectedOrder: {},
      loading: false,
      searchForm: {
        orderId: '',
        status: '',
        orderType: '',
      },
    };
  },
  computed: {
    adminInfo() {
      return this.$store.state.adminInfo || JSON.parse(sessionStorage.getItem('adminInfo')) || {
        username: '超级星',
        role: 'super'
      };
    },
    isSuperAdmin() {
      return this.adminInfo.role === 'super';
    },
    filteredOrders() {
      // 如果 orderId 不为空，则在前端进行过滤
      if (this.searchForm.orderId !== '' && this.searchForm.orderId !== null) {
        const orderIdNum = Number(this.searchForm.orderId);
        return this.selfServiceOrders.filter(order => order.orderId === orderIdNum);
      }
      return this.selfServiceOrders;
    }
  },
  mounted() {
    this.fetchOrders();
  },
  methods: {
    fetchOrders: _.debounce(async function() {
      try {
        this.loading = true;
        const token = sessionStorage.getItem('token');
        if (!token) {
          this.$message.error('未登录，请先登录');
          return;
        }
        const response = await axios.get('/api/self-service-orders', {
          params: {
            page: this.currentPage,
            size: this.pageSize,
            orderId: this.searchForm.orderId || null,  // 添加 orderId 参数
            status: this.searchForm.status || null,
            orderType: this.searchForm.orderType || null,
          },
          headers: {
            Authorization: `Bearer ${token}`,
            'Role': encodeURIComponent(this.adminInfo.role || ''),
            'Username': encodeURIComponent(this.adminInfo.username || ''),
          },
        });
        this.selfServiceOrders = response.data.data || [];
        this.totalOrders = response.data.total || 0;
        if (this.selfServiceOrders.length === 0 && this.totalOrders > 0) {
          console.warn('No orders returned despite total > 0, possible backend logic or data issue');
        }
      } catch (error) {
        this.$message.error('获取订单列表失败: ' + (error.response?.data?.message || error.message));
        console.error('Error fetching orders:', error.response ? error.response.data : error);
      } finally {
        this.loading = false;
      }
    }, 300),

    handleSearch() {
      this.currentPage = 1;
      this.fetchOrders();
    },

    resetSearch() {
      this.searchForm = { orderId: '', status: '', orderType: '' };
      this.currentPage = 1;
      this.fetchOrders();
    },

    handlePageChange(newPage) {
      this.currentPage = newPage;
      this.fetchOrders();
    },

    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.fetchOrders();
    },

    viewOrderDetails(order) {
      this.selectedOrder = { ...order };
      this.dialogVisible = true;
    },

    deleteOrder(orderId) {
      this.$confirm('确定删除此订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(async () => {
            try {
              const token = sessionStorage.getItem('token');
              await axios.delete(`/api/self-service-orders/${orderId}`, {
                headers: {
                  Authorization: `Bearer ${token}`,
                  'Role': encodeURIComponent(this.adminInfo.role || ''),
                  'Username': encodeURIComponent(this.adminInfo.username || ''),
                },
              });
              this.$message.success('订单删除成功');
              this.fetchOrders();
            } catch (error) {
              this.$message.error('删除订单失败: ' + (error.response?.data?.message || error.message));
              console.error('Error deleting order:', error.response ? error.response.data : error);
            }
          })
          .catch(() => {
            this.$message.info('已取消删除');
          });
    },

    statusText(status) {
      const map = {
        pending: '待处理',
        washing: '洗涤中',
        ready_for_pickup: '准备取件',
        completed: '已完成',
      };
      return map[status] || status;
    },

    paymentStatusText(paymentStatus) {
      const map = {
        success: '已支付',
        failed: '支付失败',
        pending: '待支付',
      };
      return map[paymentStatus] || paymentStatus;
    },

    getStatusTagType(status) {
      const map = {
        pending: 'info',
        washing: 'primary',
        ready_for_pickup: 'warning',
        completed: 'success',
      };
      return map[status] || '';
    },

    getPaymentStatusTagType(paymentStatus) {
      const map = {
        success: 'success',
        failed: 'danger',
        pending: 'info',
      };
      return map[paymentStatus] || '';
    },

    formatDateTime(dateTime) {
      if (!dateTime) return 'N/A';
      const date = new Date(dateTime);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false,
      }).replace(/\//g, '-');
    },
  },
};
</script>

<style scoped>
.order-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

h2 {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}

.search-filter {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.el-table {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>